<template>
  <div class="forum-detail-page">
    <el-button type="text" icon="el-icon-arrow-left" @click="$router.push({ path: '/home', query: { tab: 'forum' } })" style="margin-bottom: 18px;">
      返回论坛
    </el-button>
    <el-card class="post-card" v-if="post">
      <div class="post-title-row">
        <div class="post-title">{{ post.title }}</div>
        <button
          class="like-btn"
          :class="{ liked: liked }"
          @click="toggleLike"
          :disabled="likeLoading"
          :title="liked ? '取消点赞' : '点赞'"
        >
          <span class="heart" :class="{ liked: liked }">❤</span>
          <span class="like-count">{{ likeCount }}</span>
        </button>
        <el-button
          v-if="post.userId === currentUserId"
          type="danger"
          size="mini"
          @click="deletePost"
          style="margin-left:10px;"
        >删除帖子</el-button>
      </div>
      <div class="post-meta">
        <span>作者ID：{{ post.userId }}</span>
        <span>发布时间：{{ formatDate(post.createdAt) }}</span>
        <span>浏览量：{{ post.views }}</span>
      </div>
      <div class="post-content markdown-body" v-html="renderedContent"></div>
    </el-card>

    <el-card class="comment-card">
      <div class="comment-header">
        <span>评论（{{ comments.length }}）</span>
      </div>
      <div v-if="comments.length === 0" class="no-comment">暂无评论</div>
      <el-timeline>
        <el-timeline-item
          v-for="comment in comments"
          :key="comment.id"
          :timestamp="formatDate(comment.createdAt)"
          placement="top"
        >
          <div class="comment-item">
            <span class="comment-user">用户ID：{{ comment.userId }}</span>
            <span class="comment-content">{{ comment.content }}</span>
            <el-button
              v-if="comment.userId === currentUserId"
              type="text"
              size="mini"
              @click="deleteComment(comment.id)"
              style="color:#F56C6C;margin-left:10px;"
            >删除</el-button>
          </div>
        </el-timeline-item>
      </el-timeline>
      <div class="add-comment-row">
        <el-input
          v-model="newComment"
          placeholder="写下你的评论..."
          size="medium"
          maxlength="200"
          show-word-limit
          @keyup.enter.native="addComment"
        />
        <el-button type="primary" @click="addComment" :loading="commentLoading" style="margin-left:10px;">发表评论</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { marked } from 'marked';

export default {
  name: "ForumPostDetail",
  data() {
    return {
      post: null,
      renderedContent: '',
      comments: [],
      newComment: '',
      commentLoading: false,
      currentUserId: null,
      likeCount: 0,
      liked: false,
      likeLoading: false
    }
  },
  methods: {
    async fetchPost() {
      const postId = this.$route.params.id;
      try {
        const res = await this.axios.get(`/api/forum/posts/${postId}`);
        this.post = res.data;
        this.renderedContent = marked.parse(this.post.content || '');
        this.fetchLikeCount();
        this.fetchLikedStatus();
      } catch (e) {
        this.$message.error('获取帖子失败');
      }
    },
    async fetchComments() {
      const postId = this.$route.params.id;
      try {
        const res = await this.axios.get(`/api/forum/comments/post/${postId}`);
        this.comments = res.data || [];
      } catch (e) {
        this.$message.error('获取评论失败');
      }
    },
    async addComment() {
      if (!this.newComment.trim()) {
        this.$message.warning('评论内容不能为空');
        return;
      }
      this.commentLoading = true;
      try {
        const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
        const userId = userInfo.id;
        if (!userId) {
          this.$message.error('请先登录');
          this.commentLoading = false;
          return;
        }
        await this.axios.post('/api/forum/comments', {
          postId: Number(this.$route.params.id),
          userId,
          content: this.newComment.trim()
        });
        this.$message.success('评论成功');
        this.newComment = '';
        this.fetchComments();
      } catch (e) {
        this.$message.error('评论失败');
      } finally {
        this.commentLoading = false;
      }
    },
    async deleteComment(commentId) {
      try {
        await this.axios.delete(`/api/forum/comments/${commentId}`);
        this.$message.success('删除成功');
        this.fetchComments();
      } catch (e) {
        this.$message.error('删除失败');
      }
    },
    async deletePost() {
      this.$confirm('确定要删除这篇帖子吗？', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.axios.delete(`/api/forum/posts/${this.post.id}`);
          this.$message.success('帖子已删除');
          this.$router.push({ path: '/home', query: { tab: 'forum' } });
        } catch (e) {
          this.$message.error('删除失败');
        }
      }).catch(() => {});
    },
    formatDate(date) {
      if (typeof date === 'string') date = new Date(date);
      if (!(date instanceof Date) || isNaN(date.getTime())) return '';
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, '0');
      const d = String(date.getDate()).padStart(2, '0');
      const h = String(date.getHours()).padStart(2, '0');
      const min = String(date.getMinutes()).padStart(2, '0');
      return `${y}-${m}-${d} ${h}:${min}`;
    },
    async fetchLikeCount() {
      const postId = this.$route.params.id;
      try {
        const res = await this.axios.get(`/api/forum/posts/${postId}/likes`);
        this.likeCount = res.data;
      } catch (e) {
        this.likeCount = 0;
      }
    },
    async fetchLikedStatus() {
      const postId = this.$route.params.id;
      const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
      const userId = userInfo.id;
      this.liked = false;
    },
    async toggleLike() {
      if (this.likeLoading) return;
      this.likeLoading = true;
      const postId = this.$route.params.id;
      const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
      const userId = userInfo.id;
      if (!userId) {
        this.$message.error('请先登录');
        this.likeLoading = false;
        return;
      }
      try {
        const res = await this.axios.post(`/api/forum/posts/${postId}/like`, null, {
          params: { userId }
        });
        if (res.data === "Liked") {
          this.liked = true;
          this.$message.success('点赞成功');
        } else {
          this.liked = false;
          this.$message.success('已取消点赞');
        }
        this.fetchLikeCount();
      } catch (e) {
        this.$message.error('操作失败');
      } finally {
        this.likeLoading = false;
      }
    }
  },
  created() {
    const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
    this.currentUserId = userInfo.id;
    this.fetchPost();
    this.fetchComments();
    this.fetchLikeCount();
    this.fetchLikedStatus();
  }
}
</script>

<style scoped>
.forum-detail-page {
  max-width: 900px;
  margin: 0 auto;
  padding: 30px 0 40px 0;
}
.post-card {
  margin-bottom: 24px;
  border-radius: 12px;
}
.post-title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.post-title {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}
.post-meta {
  color: #888;
  font-size: 14px;
  margin-bottom: 18px;
  display: flex;
  gap: 24px;
}
.post-content {
  font-size: 18px;
  color: #222;
  line-height: 1.8;
  margin-bottom: 10px;
  word-break: break-all;
}
.comment-card {
  border-radius: 12px;
  margin-bottom: 20px;
}
.comment-header {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}
.no-comment {
  color: #aaa;
  font-size: 15px;
  margin-bottom: 10px;
}
.comment-item {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
}
.comment-user {
  color: #67C23A;
  font-size: 15px;
  margin-right: 8px;
}
.add-comment-row {
  display: flex;
  align-items: center;
  margin-top: 18px;
  gap: 10px;
}
.like-btn {
  background: none;
  border: none;
  outline: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  padding: 4px 10px;
  margin-left: 10px;
  transition: background 0.2s;
  border-radius: 20px;
}
.like-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
.heart {
  font-size: 24px;
  color: #bbb;
  transition: color 0.2s, transform 0.2s;
  margin-right: 6px;
}
.heart.liked {
  color: #F56C6C;
  transform: scale(1.2);
}
.like-btn.liked .heart {
  color: #F56C6C;
}
.like-btn:hover .heart {
  color: #F56C6C;
  transform: scale(1.2);
}
.like-count {
  font-size: 18px;
  color: #F56C6C;
  font-weight: bold;
  vertical-align: middle;
}
</style> 